const Router = require('@koa/router');
const { MapWay, Item, PlayableClass, Toy } = require('../db/schemas')

const { Language } = require('../env');
const { genResponse } = require('../utils');

const router = new Router({ prefix: '/map-way', strict: false })

function escapeRegExp(keyword) {
  return keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

router.get('/', async (ctx) => {
  const { current, pageSize, keyword = '' } = ctx.query;

  const page = parseInt(current);
  const page_size = parseInt(pageSize);

  const trimmedKeyword = keyword.trim();
  const escapedKeyword = trimmedKeyword ? escapeRegExp(trimmedKeyword) : '';

  const searchQuery = trimmedKeyword
    ? { name: { $regex: escapedKeyword, $options: 'i' } }
    : {};

  const sort = { create_at: -1 };

  const aggregationPipeline = [
    { $match: searchQuery },
    { $sort: sort },
    {
      $facet: {
        results: [
          { $skip: (page - 1) * page_size },
          { $limit: page_size }
        ],
        total: [
          { $count: 'total' }
        ]
      }
    }
  ];
  const aggregationResult = await MapWay.aggregate(aggregationPipeline)

  const results = aggregationResult[0].results; // 分页数据
  const total = aggregationResult[0].total[0]?.total || 0; // 总数（可能为0）
  const totalPages = Math.ceil(total / page_size); // 总页数

  ctx.body = genResponse(true, { results, total: totalPages })
})

router.post('/', async (ctx) => {
  const record = await MapWay.findOne({ id: parseInt(ctx.request.body.id) })
  if (record) {
    ctx.throw(400, '记录已存在')
  }
  const doc = new MapWay(ctx.request.body)
  await doc.save()
  ctx.body = genResponse(true, doc)
})

router.put('/:id', async (ctx) => {
  const id = parseInt(ctx.request.body.id || ctx.params.id)
  const record = await MapWay.findOneAndUpdate({ id }, ctx.request.body)
  ctx.body = genResponse(true, record)
})

router.delete('/:id', async (ctx) => {
  const id = parseInt(ctx.params.id)
  const record = await MapWay.findOneAndDelete({ id: id })
  ctx.body = genResponse(true, record)
})

const ModelMap = {
  CLASS: {
    match: `name.${Language}`,
    model: PlayableClass,
    project: {
      id: 1,
      name: `$name.${Language}`
    }
  },
  TOY: {
    match: `item.name.${Language}`,
    model: Toy,
    project: {
      id: 1,
      name: `$item.name.${Language}`
    }
  },
  ITEM: {
    match: `name.${Language}`,
    model: Item,
    project: {
      id: 1,
      name: `$name.${Language}`
    }
  },
}
router.get('/find', async (ctx) => {
  const { type, keyword } = ctx.query
  const trimmedKeyword = keyword.trim();
  const escapedKeyword = trimmedKeyword ? escapeRegExp(trimmedKeyword) : '';
  // console.log('[/find]', type, escapedKeyword);
  const model = ModelMap[type];

  // console.log('escapedKeyword', escapedKeyword);
  const searchQuery = trimmedKeyword
    ? { [model.match]: { $regex: escapedKeyword, $options: 'i' } }
    : {};

  // const sort = { create_at: -1 };

  const aggregationPipeline = [
    { $match: searchQuery },
    { $project: model.project },
  ];
  const results = await model.model.aggregate(aggregationPipeline)
  ctx.body = genResponse(true, { results, total: results.length })
})

module.exports = router